import CryptoJS from "crypto-js";

export const AESEncryption = (secret: string, str: string): string => {
  if (typeof str !== "string") {
    try {
      str = (str as number).toString();
    } catch (e) {
      throw new Error("The type of encrypted data should be a string");
    }
  }
  let key = CryptoJS.enc.Utf8.parse(secret);
  let encrypted = CryptoJS.AES.encrypt(str.toString(), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

export const AESDecryption = (secret: string, data: any): string => {
  let key = CryptoJS.enc.Utf8.parse(secret);
  let decrypted = CryptoJS.AES.decrypt(data, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  }).toString(CryptoJS.enc.Utf8);
  return decrypted;
};
